package com.wd.live.view.fragment;


import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.wd.live.R;
import com.wd.live.base.BaseFragment;
import com.wd.live.bean.SquareLiveBean;
import com.wd.live.databinding.NearFragmentBinding;
import com.wd.live.model.SpUtils;
import com.wd.live.viewmodel.MainViewModel;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenu;
import com.yanzhenjie.recyclerview.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.HashMap;
import java.util.List;

/**
 * <p>项目名称:LookFor2.0</p>
 * <p>包名:com.bawei.lookfor20.view</p>
 * <p>简述:</p>
 *
 * @author 孟令高
 * @date 2022/11/9
 */
public class NearFragment extends BaseFragment<MainViewModel, NearFragmentBinding> {
    private PopupWindow popupWindow;
    public AMapLocationClient client = null;
    private double aDouble;
    private double aDouble1;
    private int sex = 0;
    private HashMap<String, Object> map;
    private List<SquareLiveBean.ResultBean> result = null;
    private Integer userid;

    @Override
    protected void initData() {
        String uid = SpUtils.getString("uid", "");
        userid = Integer.valueOf(uid);
        map = new HashMap<>();
        boolean checkBox = SpUtils.getBoolean("CheckBox",false);
        if(checkBox){
            //显示雷达图
            databind.nearDingwei.setVisibility(View.VISIBLE);
            //隐藏未开定位图片与文字
            databind.nearimg1.setVisibility(View.GONE);
            databind.text.setVisibility(View.GONE);
            //列表
            databind.swipeRec.setVisibility(View.VISIBLE);
            location();//获取当前定位
        }
        //弹窗获取开启定位
        View inflate = LayoutInflater.from(getContext()).inflate(R.layout.pop_near, null);
        databind.dakai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow = new PopupWindow(inflate,
                        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, false);
                popupWindow.showAtLocation(inflate, Gravity.CENTER, 0, 0);
                popupWindow.setTouchable(true);
            }
        });
        //弹窗禁止按钮
        inflate.findViewById(R.id.jinzhi).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        //确认
        inflate.findViewById(R.id.kaisyhi).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //显示雷达图
                databind.nearDingwei.setVisibility(View.VISIBLE);
                //隐藏未开定位图片与文字
                databind.nearimg1.setVisibility(View.GONE);
                databind.text.setVisibility(View.GONE);
                //列表
                databind.swipeRec.setVisibility(View.VISIBLE);
                location();//获取当前定位
                SpUtils.putBoolean("CheckBox", true);
                //动态获取当前位置
                initPermissions();
                popupWindow.dismiss();
            }
        });
        //观看性别
        databind.nearRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.nearrb1) {
                    sex = 0;
                } else if (checkedId == R.id.nearrb2) {
                    sex = 1;
                } else if (checkedId == R.id.nearrb3) {
                    sex = 2;
                }
                getlist(aDouble1 +"", aDouble +"",sex,5000);

            }
        });
        //复选框
        CheckBox pop = inflate.findViewById(R.id.popcheckbox);
        pop.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Log.e("CheckBox:::", "选中");
                    SpUtils.putBoolean("CheckBox", true);
                } else {
                    Log.e("CheckBox:::", "取消");
                    SpUtils.putBoolean("CheckBox", false);
                }
            }
        });



        //刷新
        databind.refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //动画旋转
                Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.below_img);
                databind.refresh.startAnimation(animation);
                //动画监听
                animation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        getlist(aDouble1 +"", aDouble +"",sex,5000);//获取列表数据
                        Toast.makeText(getContext(), "刷新成功", Toast.LENGTH_SHORT).show();
                    }
                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }
        });
    }



    @Override
    public void onResume() {
        super.onResume();
        databind.swipeRec.setSwipeMenuCreator(new SwipeMenuCreator() {
            @Override
            public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int position) {
                SwipeMenuItem swipeMenuItem = new SwipeMenuItem(getContext())
                        .setText("进入直播间")
                        .setTextColor(Color.WHITE)
                        .setHeight(400)
                        .setWidth(400)//菜单宽度
                        .setBackground(R.drawable.nearbackgroundsideslip)
                        .setHeight(RecyclerView.LayoutParams.MATCH_PARENT);//菜单高度
                rightMenu.addMenuItem(swipeMenuItem);
            }
        });
        databind.swipeRec.setOnItemMenuClickListener(new OnItemMenuClickListener() {
            @Override
            public void onItemClick(SwipeMenuBridge menuBridge, int adapterPosition) {
                Toast.makeText(getContext(), "进入直播间", Toast.LENGTH_SHORT).show();

            }
        });
    }
    public AMapLocationListener mapLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    //维度
                    aDouble = aMapLocation.getLatitude();
                    //经度
                    aDouble1 = aMapLocation.getLongitude();
                    String province = aMapLocation.getProvince();
                    String city = aMapLocation.getCity();
                    String district = aMapLocation.getDistrict();
                    String streetNumber = aMapLocation.getStreetNum();
                    String text = "" + province + city + district + streetNumber;
                    databind.nearName.setText(text+"北京市海淀区");
                    getlist(aDouble1 +"", aDouble +"",0,5000);//获取列表数据
                    Log.i("jingwei", "经度" + aDouble + "纬度" + aDouble1);
                } else {
                    Log.e("AmapError", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                    databind.  nearName.setText("定位失败");
                }
            }
        }
    };
    public AMapLocationClientOption mLocationOption = null;
    private void location() {

        AMapLocationClient.updatePrivacyShow(getContext(), true, true);
        AMapLocationClient.updatePrivacyAgree(getContext(), true);
        try {
            client = new AMapLocationClient(getContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
        client.setLocationListener(mapLocationListener);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        if (null != client) {
            client.setLocationOption(mLocationOption);
            client.stopLocation();
            client.startLocation();
        }

    }
    public void onDestroy() {
        super.onDestroy();
        if (client != null){
            client.onDestroy();
        }
        if (result != null){
            result.clear();
        }
    }

    @Override
    protected int initLayout() {
        return R.layout.near_fragment;
    }

    @Override
    public void onChanged(Object o) {

    }
    private void getlist(String s, String s1, int sex, int i) {
        viewmodel.getfindNearbylive(userid,s, s1 + "", sex, i).observe(getActivity(), new Observer<SquareLiveBean>() {
            @Override
            public void onChanged(SquareLiveBean liveBean) {
                List<SquareLiveBean.ResultBean> result = liveBean.getResult();
                databind.swipeRec.setLayoutManager(new LinearLayoutManager(getContext()));
                databind.swipeRec.setAdapter(new CommonAdapter<SquareLiveBean.ResultBean>(getContext(), R.layout.near_rec, result) {
                    @Override
                    protected void convert(ViewHolder holder, SquareLiveBean.ResultBean resultBean, int position) {
                        Glide.with(mContext).load(resultBean.getHeadPic())
                                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                                .error(R.mipmap.zhanweitu)
                                .placeholder(R.mipmap.zhanweitu)
                                .into((ImageView) holder.getView(R.id.imgsearch));//头像
                        holder.setText(R.id.namesearch, resultBean.getNickName());//名称
                        holder.setText(R.id.qianming, "");
                        ImageView imgsex = holder.getView(R.id.imgsex);
                        if (resultBean.getSex() == 1) {
                            imgsex.setImageResource(R.mipmap.man);
                        } else {
                            imgsex.setImageResource(R.mipmap.gerry);
                        }
                    }
                });
            }
        });//获取列表数据
    }
    //权限数组（申请定位）
    private String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS};

    //返回code
    private static final int OPEN_SET_REQUEST_CODE = 100;

    //调用此方法判断是否拥有权限
    private void initPermissions() {
        if (lacksPermission(permissions)) {//判断是否拥有权限
            //请求权限，第二参数权限String数据，第三个参数是请求码便于在onRequestPermissionsResult 方法中根据code进行判断
            ActivityCompat.requestPermissions(getActivity(), permissions, OPEN_SET_REQUEST_CODE);
        } else {
            //拥有权限执行操作
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {//响应Code
            case OPEN_SET_REQUEST_CODE:
                if (grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                            Toast.makeText(getContext(), "未拥有相应权限", Toast.LENGTH_LONG).show();
                            return;
                        }
                    }
                    //拥有权限执行操作
                } else {
                    Toast.makeText(getContext(), "未拥有相应权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    //如果返回true表示缺少权限
    public boolean lacksPermission(String[] permissions) {
        for (String permission : permissions) {
            //判断是否缺少权限，true=缺少权限
            if (ContextCompat.checkSelfPermission(getContext(), permission) != PackageManager.PERMISSION_GRANTED) {
                return true;
            }
        }
        return false;
    }


}